<?php
/**
*
* @package phpBB3 stockvirtual
* @version $Id$
* @copyright (c) 2005 phpBB Group, 2011 Minway Hsu
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
*/

/**
* @ignore
*/
function list_user_roi_ranking($period = 30, $list = 'roi_1_month_list',$max = 20, $user_id = 0, $fb_friends = '', $list_to_user_id = 0, $only_fb_user = false)
{
	global	$db, $template;
	
	$show = false;
	
	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - 90 * 24 * 60 *60;
	
	if ($fb_friends == '')
	{
		$sql	= "SELECT user_id, roi FROM sv_user_roi WHERE period = $period AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY roi DESC";
		
		// If we only FB users, don't set limit in SQL queries.
		if ($only_fb_user)
			$result = $db->sql_query($sql); 
		else
			$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
				continue;
				
			// Send vars to template
			$template->assign_block_vars($list, array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'ROI'							=> round($row['roi']*100, 1),
				)
			);
			++$i;
			$show = true;
			
			if ($list_to_user_id != 0 && $list_to_user_id == $row['user_id'])
			{
				break;
			}
			if ($only_fb_user && $i > $max)
			{
				break;
			}
		}
	}
	else
	{	
		$sql	= "SELECT user_id, roi FROM sv_user_roi WHERE (user_id=$user_id OR user_id IN ($fb_friends)) AND period = $period ORDER BY roi DESC";
		$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			// Send vars to template
			$template->assign_block_vars($list, array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'ROI'							=> round($row['roi']*100, 1),
				)
			);
			++$i;
			$show = true;
		}
	}
	
	return $show;
}

// max: max records to show.
// user_id: the current user id. Only used in FB friends ranking page.
// fb_friends: a strings contains all FB friends. Only used in FB friends ranking page.
// list_to_user_id: list all records until the current user. 
function list_user_value_ranking($max = 30, $user_id = 0, $fb_friends = '', $list_to_user_id = 0, $only_fb_user = false)
{
	global	$db, $template, $date;
	
	$show = false;

	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - 90 * 24 * 60 *60;
	
	// On normal ranking page.
	if ($fb_friends == '')
	{
		// list highest 30 user values in the latest date. 
		$sql	= "SELECT user_id, value, money, date FROM sv_user_value WHERE date = (SELECT MAX( date ) FROM sv_user_value ) AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY value DESC";
		
		// If we only FB users, don't set limit in SQL queries.
		if ($only_fb_user)
			$result = $db->sql_query($sql); 
		else
			$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{
			if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
				continue;
				
			// Send vars to template
			$template->assign_block_vars('list', array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				)
			);
			++$i;
			$show = true;
			$date = $row['date'];
			
			if ($list_to_user_id != 0 && $list_to_user_id == $row['user_id'])
			{
				break;
			}
			if ($only_fb_user && $i > $max)
			{
				break;
			}
		}
	}
	// on FB friends ranking page.
	else
	{
		$sql	= "SELECT * FROM `sv_user_value` WHERE (user_id=$user_id OR user_id IN ($fb_friends)) AND date = (SELECT MAX( date ) FROM sv_user_value ) ORDER BY value DESC";
		$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			// Send vars to template
			$template->assign_block_vars('list', array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				)
			);
			++$i;
		
			$show = true;	
			$date = $row['date'];
		}
	}

	return $show;
}

function include_nav_links()
{
	global $template, $phpbb_root_path, $phpEx, $in_fb_iframe,$user_id;
	
	$is_following_anyone = is_following_anyone($user_id);
	
	// Assign index specific vars
	if ($in_fb_iframe)
	{
		$template->assign_vars(array(
			'S_SV_INDEX'					=> append_sid("{$phpbb_root_path}fb/index.$phpEx", ''),
			'S_BUY_ACTION'					=> append_sid("{$phpbb_root_path}fb/buy.$phpEx", ''),
			'S_SELL_ACTION'					=> append_sid("{$phpbb_root_path}fb/sell.$phpEx", ''),
			'S_PERFORMANCE_ACTION'			=> append_sid("{$phpbb_root_path}fb/performance.$phpEx", ''),
			'S_RANKING_ACTION'				=> append_sid("{$phpbb_root_path}fb/ranking.$phpEx", ''),
			'S_RULE'						=> append_sid("{$phpbb_root_path}fb/rule.$phpEx", ''),
			'S_FOLLOW_INFO'					=> append_sid("{$phpbb_root_path}fb/follow_info.$phpEx", ''),
			
			'IS_FOLLOWING_ANYONE'			=>	$is_following_anyone,
		));
	}
	else
	{
		$template->assign_vars(array(
			'S_SV_INDEX'					=> append_sid("{$phpbb_root_path}index.$phpEx", ''),
			'S_BUY_ACTION'					=> append_sid("{$phpbb_root_path}buy.$phpEx", ''),
			'S_SELL_ACTION'					=> append_sid("{$phpbb_root_path}sell.$phpEx", ''),
			'S_PERFORMANCE_ACTION'			=> append_sid("{$phpbb_root_path}performance.$phpEx", ''),
			'S_RANKING_ACTION'				=> append_sid("{$phpbb_root_path}ranking.$phpEx", ''),
			'S_RULE'						=> append_sid("{$phpbb_root_path}rule.$phpEx", ''),
			'S_FOLLOW_INFO'					=> append_sid("{$phpbb_root_path}follow_info.$phpEx", ''),
			
			'IS_FOLLOWING_ANYONE'			=>	$is_following_anyone,
		));
	}
	
}

// list recent related equity change events.
function list_equity_change_event($query_user_id)
{
	global	$db, $equity_change_event_list, $template;
		
	$equity_change_event_list = false;
	
	$sql 	= 'SELECT * FROM sv_holding_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		$corp_id = $row['corp_id'];
		
		$sql2		= 'SELECT * FROM sv_equity_change_event WHERE corp_id="' . $corp_id . '" AND status="new"';
		$result2	= $db->sql_query($sql2); 
		while ($row2 = $db->sql_fetchrow($result2))
		{
			$equity_change_event_list = true;
			
			$share_unit				= $row2['share_unit'];
			$cash_after_change 		= $row2['cash_after_change'];
			$corp_id_after_change 	= $row2['corp_id_after_change'];
			$share_after_change 	= $row2['share_after_change'];
			$corp_id_after_change_2 = $row2['corp_id_after_change_2'];
			$share_after_change_2 	= $row2['share_after_change_2'];
			$corp_id_after_change_3 = $row2['corp_id_after_change_3'];
			$share_after_change_3 	= $row2['share_after_change_3'];
			$scheduled_date 		= $row2['scheduled_date'];
			$execution_date 		= $row2['execution_date'];

			// we should display the share unit as 1000. 
			if ($share_unit != 1000)
			{
				$m = $share_unit/1000;			
				$share_unit 			/= $m;	
				$cash_after_change		/= $m;
				$share_after_change		/= $m;
				$share_after_change_2 	/= $m;
				$share_after_change_3 	/= $m;
			}
			
			// Send vars to template
			$template->assign_block_vars('equity_change_event_list', array(		
				'CORP_ID'							=> $corp_id,
				'CORP_NAME'							=> get_corp_chinese_name($corp_id),
				'SHARE_UNIT'						=> $share_unit,		
				'CASH_AFTER_CHANGE'					=> $cash_after_change,
				'CORP_ID_AFTER_CHANGE'				=> $corp_id_after_change,
				'CORP_NAME_AFTER_CHANGE'			=> get_corp_chinese_name($corp_id_after_change),
				'SHARE_AFTER_CHANGE' 				=> $share_after_change,
				'CORP_ID_AFTER_CHANGE_2'			=> $corp_id_after_change_2,
				'CORP_NAME_AFTER_CHANGE_2'			=> get_corp_chinese_name($corp_id_after_change_2),
				'SHARE_AFTER_CHANGE_2' 				=> $share_after_change_2,
				'CORP_ID_AFTER_CHANGE_3'			=> $corp_id_after_change_3,
				'CORP_NAME_AFTER_CHANGE_3'			=> get_corp_chinese_name($corp_id_after_change_3),
				'SHARE_AFTER_CHANGE_3' 				=> $share_after_change_3,
				'SCHEDULED_DATE' 					=> get_date_string($scheduled_date),
				)
			);		
		}
	}	
}


// list all open to_buy delegation. 
function list_open_to_buy_delegation()
{
	global	$db, $to_buy_delegation_list, $template, $user_id;
	
	$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_buy"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_buy_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = date('Y.m.d H:i:s', (int)$row['check_time']);
		}
	
		// Send vars to template
		$template->assign_block_vars('to_buy_delegation_list', array(		
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share']/1000,			
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
}

// list all open to_sell delegation. 
function list_open_to_sell_delegation()
{
	global	$db, $to_sell_delegation_list, $template, $user_id;
	
	$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_sell"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_sell_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = date('Y.m.d H:i:s', (int)$row['check_time']);
		}
		
		// Send vars to template
		$template->assign_block_vars('to_sell_delegation_list', array(
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share']/1000,			
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
}

// list all holding stock.
function list_holding_stock($query_user_id = '', $show_stock_max = 0, $detail_url = '')
{
	global	$db, $holding_stock_list, $template, $user_id, $user;
		
	if ($query_user_id == '')
	{
		$query_user_id = $user_id;
	}
	
	$not_all_stock_showed = false;
	
	// get the user money.
	$sql	= 'SELECT * FROM phpbb_users WHERE user_id=' . $query_user_id;
	$result	= $db->sql_query_limit($sql, 1);
	$row	= $db->sql_fetchrow($result);
	$money 	= $row['user_money'];
			
	$value 	= $money;
	
	$pie_value = array();
		
	// calculate total market value.
	$sql 	= 'SELECT * FROM sv_holding_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		$refered_price	 		= get_refered_price($row['corp_id']);
		$market_value 			= $refered_price * $row['share'];
		$value 					+= $market_value;
	}
		
	$template->assign_vars(array(
			'TOTAL_VALUE_IN_HOLDING_STOCK_LIST'				=> number_format($value),
			'MONEY_IN_HOLDING_STOCK_LIST'					=> number_format($money),
			'VALUE_IN_HOLDING_STOCK_LIST'					=> number_format($value - $money),
		));
	
	// Assign index specific vars
	if ($value != 0)
	{		
		$per	= round($money*100/$value, 0);
		$name 	= ' ' . "現金 " . $per . '%';
		$pie_value[] = new pie_value($per, $name);	
	
		$template->assign_vars(array(
			'MONEY_PERCENTAGE_IN_HOLDING_STOCK_LIST'		=> round($money*100/$value, 1),
			'VALUE_PERCENTAGE_IN_HOLDING_STOCK_LIST'		=> round(($value - $money)*100/$value, 1),
		));
	}
		
	// list all holding stocks.	
	$sql 	= 'SELECT * FROM sv_holding_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	$i = 1;
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$holding_stock_list = true;
		
		$refered_price	 		= get_refered_price($row['corp_id']);
		$cost 					= (float)$row['cost'];
		$market_value 			= $refered_price * $row['share'];
		$market_value_percent	= '';
		if ($value != 0)
		{
			$market_value_percent = round($market_value * 100 / $value, 0);
		}
		$difference_price_percent = '';
		if ($cost != 0)
		{
			$difference_price_percent = round(($refered_price - $cost)*100/$cost, 1);
		}
		
		// Check if we exceed the max stock number.
		if ($show_stock_max != 0 && $i > $show_stock_max)
		{
			$not_all_stock_showed = true;			
		}
		else
		{
			// Send vars to template
			$template->assign_block_vars('holding_stock_list', array(
				'CORP_ID'						=> $row['corp_id'],
				'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
				'NUMBER'						=> (int)$row['share']/1000,
				'COST'							=> round($cost, 1),
				'REFERED_PRICE'					=> $refered_price,
				'DIFFERENCE_PRICE'				=> round($refered_price - $cost, 1),
				'DIFFERENCE_PRICE_PERCENT'		=> $difference_price_percent,
				'MARKET_VALUE'					=> round($market_value, 0),
				'MARKET_VALUE_PERCENT'			=> $market_value_percent,
				
				)
			);		
		}		
		
		if ($value != 0)
		{
			// Add pie value to pie chart.
			$per	= round($market_value * 100 / $value, 0);
			$name 	= ' ' . get_corp_chinese_name($row['corp_id']) . '(' . $row['corp_id'] . ') ' . $per . '%';
			$pie_value[] = new pie_value($per, $name);
		}
		
		$i += 1;
		
		
	}
	
	$template->assign_vars(array(
			'NOT_ALL_STOCK_SHOWED'					=> $not_all_stock_showed,
			'HOLDING_STOCK_DETAIL_URL'				=> $detail_url,
			));
			
	if ($value != 0)
	{
		// draw the pie chart.
		$title = new title( '' );	
	
		$pie = new pie();
		$pie->set_start_angle( 0 );
		$pie->set_animate( true );
		$pie->set_tooltip( '#percent# ' );
		$pie->set_values($pie_value);
//		$pie->set_colours( array( '#FF0000', '#FF8000', '#8F8F00', '#00BF00','#0080FF', '#0000FF','#8000FF','#454545') );
//		$pie->set_colours( array( '#74AAC6', '#7E7367', '#BD665B', '#E88896','#B0CABB', '#EB996C','#B8C853','#F85546', '#EED307') );
//		$pie->set_colours( array( '#649AB6', '#6E6357', '#AD564B', '#D87886','#A0BAAB', '#DB895C','#A8B843','#E84536', '#DEC307') );
		$pie->set_colours( array( '#548AA6', '#5E5347', '#9D463B', '#C86876','#90AA9B', '#CB794C','#98A833','#D83526', '#CEB307') );
	
		$chart = new open_flash_chart();
		$chart->set_title( $title );
		$chart->add_element( $pie );

		$chart->x_axis = null;

		$chart->set_bg_colour('#ECF1F3');
		
		$holding_stock_jason_string = $chart->toPrettyString();	
	
		$template->assign_vars(array(
			'HOLDING_STOCK_JASON_STRING'					=> $holding_stock_jason_string,
			));
	}

}

// use open flash chart to draw user values.
function draw_user_value($user_id)
{
	global $db, $performance, $jason_string;
	
	// steps on X label.
	$steps	= 5;
	
	// get user value
	$sql 	= 'SELECT * FROM sv_user_value WHERE user_id=' . $user_id . ' ORDER BY date ASC';
	$result = $db->sql_query($sql); 
	$date	= array();
	$value	= array();
	$taiex	= array();
	$max	= 0;
	$min	= 100000000000; // just pick a number big enough for now. 
	$num	= 0;
	
	$taiex_max	= 0;
	$taiex_min	= 200000;

	$old_year	= '';
	
	while ($row = $db->sql_fetchrow($result))
	{
		$performance = true;
	
		if ($num % $steps == 0 && $old_year != get_year_from_date($row['date']))
		{
			$date[] 	= get_date_string($row['date']);
			$old_year	= get_year_from_date($row['date']);
		}
		else
		{
			$date[] 	= ' ' . get_month_from_date($row['date']) . '.' . get_day_from_date($row['date']);
		}
		
		$value[]	= (int)$row['value'];		
	
		if ($max < (int)$row['value'])
			$max = (int)$row['value'];
		if ($min > (int)$row['value'])
			$min = (int)$row['value'];
		
		// In some case(like Chinese New Year, the user valuss are calculated but the TAIEX is not updated.
		// We use the TAIEX of the previous day for simple handling.
		$index = get_taiex($row['date']);
		if ($index != '')
			$taiex_index	= (int)($index);
		
		$taiex[]		= $taiex_index;
		if ($taiex_max < $taiex_index)
			$taiex_max = $taiex_index;
		if ($taiex_min > $taiex_index)
			$taiex_min = $taiex_index;		
		
		++$num;
	}

	$basic_unit = 1000000;
	$original	= 10000000;
	$diff = ((int)(($max - $min) / $basic_unit) + 1.5) * $basic_unit;
	$grid = $diff / 10;
		
	$downward = (int)(($original - $min) / $grid) + 1;
	$upward = 10 - $downward;
	
	$chart_max = $original + $upward * $grid;
	$chart_min = $original - $downward * $grid;
	
	// prepare open-flash-chart 
	$chart = new open_flash_chart();

	$title = new title('');
	$chart->set_title( $title );
	
	
	$def = new dot();
	$def->size(3)->tooltip('#x_label#<br>市值:#val#');
	
	$line = new line();
	$line->set_colour( '#5B56B6' );
	$line->set_values( $value );
	$line->set_key( '', $num );
	$line->set_default_dot_style( $def );	
	$chart->add_element( $line );
	
	$taiex_dot = new dot();
	$taiex_dot->size(3)->tooltip('#x_label#<br>加權指數:#val#');
	
	$taiex_line	= new line();
	$taiex_line->set_colour( '#BFAFAF');
	$taiex_line->set_values( $taiex );	
	$taiex_line->set_key( '', $num );
	$taiex_line->set_default_dot_style( $taiex_dot );		
	$taiex_line->attach_to_right_y_axis();
	$chart->add_element( $taiex_line );
	
	$x_labels = new x_axis_labels();
	$x_labels->set_steps( $steps );
	$x_labels->set_vertical();
	$x_labels->set_colour( '#A2ACBA' );
	$x_labels->set_labels( $date );
	
	$x = new x_axis();
	$x->set_colour( '#424242' );
	$x->set_grid_colour( '#D7E4A3' );
	$x->set_offset( false );
	$x->set_steps(5);
	// Add the X Axis Labels to the X Axis
	$x->set_labels( $x_labels ); 
	
	$chart->set_x_axis( $x );
	
	$y = new y_axis();
	$y->set_colour( '#5B56B6' );
	$y->set_range( $chart_min, $chart_max, ($chart_max- $chart_min)/10 ); //min, max, interval
	$chart->set_y_axis( $y );
	
	$y_right = new y_axis_right();
	$y_right->set_range( $taiex_min, $taiex_max, (int)(($taiex_max - $taiex_min)/10));
	$y_right->set_stroke( 3 );
	$y_right->set_colour( '#BFAFAF' );
	$y_right->set_tick_length( 12 );
	$y_right->set_steps( (int)(($taiex_max - $taiex_min)/10));
	$chart->set_y_axis_right( $y_right );
		
	$jason_string = $chart->toPrettyString();	
}
?>